import React, { createContext, useState, useEffect, useCallback, useContext } from 'react';

import { useLocation } from 'react-router-dom';

export const NestedRouteContext = createContext();

export const useNestedRouteContext = () => {
  return useContext(NestedRouteContext);
};

export const NestedRouteProvider = ({ children }) => {
  const [routeStates, setRouteStates] = useState({});
  const [routeKeys, setRouteKeys] = useState([]); // 记录键的顺序
  const location = useLocation();

  // Save state when navigating away
  const saveRouteState = useCallback((route, state) => {
    setRouteStates(prev => ({
      ...prev,
      [route]: state
    }));
    setRouteKeys(prev => [...prev.filter(key => key !== route), route]); // 更新键的顺序
  }, []);

  // Restore state when returning to a route
  const getRouteState = useCallback((route) => {
    return routeStates[route] || null;
  }, [routeStates]);

  // Cleanup old states
  useEffect(() => {
    const MAX_STATES = 10; // Keep last 10 routes' states
    if (routeKeys.length > MAX_STATES) {
      const oldestKey = routeKeys[0];
      setRouteStates(prev => {
        const { [oldestKey]: _, ...rest } = prev;
        return rest;
      });
      setRouteKeys(prev => prev.slice(1)); // 移除最旧的键
    }
  }, [routeKeys, routeStates]);

  return (
    <NestedRouteContext.Provider value={{
      routeStates,
      saveRouteState,
      getRouteState
    }}>
      {children}
    </NestedRouteContext.Provider>
  );
};
